import { defineStore } from 'pinia'

interface UserState {
  username: string | null
  isLoggedIn: boolean
  users: Record<string, string>
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    username: null,
    isLoggedIn: false,
    users: JSON.parse(localStorage.getItem('users') || '{}')
  }),
  getters: {
    getUser: (state) => state.username,
    isAuthenticated: (state) => state.isLoggedIn
  },
  actions: {
    register(username: string, password: string) {
      if (!this.users[username]) {
        this.users[username] = password
        localStorage.setItem('users', JSON.stringify(this.users))
      }
    },
    login(username: string, password: string) {
      if (this.users[username] === password) {
        this.username = username
        this.isLoggedIn = true
        localStorage.setItem('isLoggedIn', 'true')
        localStorage.setItem('username', username)
      }
    },
    logout() {
      this.username = null
      this.isLoggedIn = false
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('username')
    },
    checkLogin() {
      const isLoggedIn = localStorage.getItem('isLoggedIn')
      const username = localStorage.getItem('username')
      if (isLoggedIn === 'true' && username) {
        this.username = username
        this.isLoggedIn = true
      }
    }
  }
})